package com.jiebao.pdascanner;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import com.jiebao.scan.ScanHelper;
import com.jiebao.scan.ScanListener;

public class MainActivity extends AppCompatActivity {
    private  LinearLayout linearLayout;

    private WebView webView;

    private WebSettings webSettings;

    private ToneGenerator tg = null;

    private  static  final  String LOAD_URL="http://259w758b32.zicp.vip/v1/static/login.html";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化扫描器
        ScanHelper.getInstance().Open_Barcode(this);
        ScanHelper.getInstance().setScanListener(scanListener);
        //初始化声音
        tg = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);

        linearLayout=new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);  // 设置垂直排列
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        setContentView(linearLayout);
        webView = new WebView(this);
        webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webSettings =  webView.getSettings();

        webSettings.setDomStorageEnabled(true);//开启DOM storage API功能
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //在Android5.0以下，默认是采用的MIXED_CONTENT_ALWAYS_ALLOW模式，
        // 即总是允许WebView同时加载Https和Http；而从Android5.0开始，默认用MIXED_CONTENT_NEVER_ALLOW模式，
        // 即总是不允许WebView同时加载Https和Http。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webSettings.setAppCacheEnabled(false);//是否使用缓存
        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webView.loadUrl(LOAD_URL);
        webView.addJavascriptInterface(new OpenScanJsInterface(),"OpenScan");
        linearLayout.addView(webView);

    }


    public class OpenScanJsInterface {
        @JavascriptInterface
        public void open() {
            BarcodeStart();
        }
    }

    private void BarcodeStart() {
        if (null !=  ScanHelper.getInstance().barcodeManager) {
            ScanHelper.getInstance().barcodeManager.Barcode_Stop();
            if (null != ScanHelper.getInstance().barcodeManager) {
                ScanHelper.getInstance().barcodeManager.Barcode_Start();
            }
        }
    }
    private ScanListener scanListener = new ScanListener() {
        @Override
        public void fillCode(final String barcode) {
            //调用js
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:scanCallback('"+barcode+"')");
                }
            });
            beep();
        }

        @Override
        public void dspStat(String content) {
        }

        @Override
        public void timeout(long timeout) {
        }
    };

    private void beep() {
        //声音
        if (tg != null) {
            tg.startTone(ToneGenerator.TONE_CDMA_NETWORK_CALLWAITING);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ScanHelper.getInstance().Close_Barcode();
    }


    /**
     * 捕获扫描物理按键广播
     */
    private BroadcastReceiver scanButtonReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.hasExtra("F4key")) {
                if (intent.getStringExtra("F4key").equals("down")) {
                    // TODO Auto-generated method stub
                    if (intent.hasExtra("F4key")) {

                        if (intent.getStringExtra("F4key").equals(" ")) {
                            BarcodeStart();
                        }

                    }
                } else if (intent.getStringExtra("F4key").equals("up")) {

                    onDestroy();
                }
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(scanButtonReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * 监听橙色按钮按键广播
         */
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.jb.action.F4key");
        registerReceiver(scanButtonReceiver, intentFilter);
    }
}
